package com.uniflow.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uniflow.common.Result;
import com.uniflow.common.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证入口点
 * 处理未认证的请求
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                        AuthenticationException authException) throws IOException, ServletException {
        
        logger.error("Unauthorized error: {}", authException.getMessage());
        
        // 设置响应头
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        
        // 构建错误响应
        Result<Object> result = Result.error(ResultCode.UNAUTHORIZED);
        
        // 根据异常类型设置具体错误信息
        String message = authException.getMessage();
        if (message != null) {
            if (message.contains("JWT") || message.contains("token")) {
                result = Result.error(ResultCode.TOKEN_INVALID);
            } else if (message.contains("expired")) {
                result = Result.error(ResultCode.TOKEN_EXPIRED);
            } else if (message.contains("Access Denied")) {
                result = Result.error(ResultCode.ACCESS_DENIED);
            }
        }
        
        // 写入响应
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}